package com.zyc.studentstudy.utils

import androidx.annotation.Nullable
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter

class SimpleFragmentPagerAdapter(
    fm: FragmentManager,
    private val mFragmentList: MutableList<Fragment>,
    private val titles: List<String>? = null
) : FragmentPagerAdapter(fm) {

    constructor(fm: FragmentManager, mFragmentList: MutableList<Fragment>) :
            this(fm, mFragmentList, null)

    override fun getItem(position: Int): Fragment = mFragmentList[position]

    override fun getCount(): Int = mFragmentList.size

    @Nullable
    override fun getPageTitle(position: Int): CharSequence? {
        return if (titles == null || position >= titles.size) null else titles[position]
    }

    override fun getItemPosition(any: Any): Int {
        return if (any is Fragment) {
            val index = mFragmentList.indexOf(any)
            if (index != -1) index else POSITION_NONE
        } else {
            super.getItemPosition(any)
        }
    }

    override fun getItemId(position: Int): Long = mFragmentList[position].hashCode().toLong()

    fun addPage(index: Int, fragment: Fragment) {
        mFragmentList.add(index, fragment)
    }

    fun addPage(fragment: Fragment) {
        mFragmentList.add(fragment)
    }

    fun delPage(index: Int) {
        mFragmentList.removeAt(index)
    }

    fun delPage(fragment: Fragment) {
        mFragmentList.remove(fragment)
    }
}
